import Base from 'models/base';

import moment from 'moment';

class BargainSituationRecord {
  constructor(record) {
    this.id = record.activityLogId;
    this.price = record.activityPrice;
    this.url = record.headimgurl;
    this.userName = record.nickname;
  }
}

export default class BargainSituationData extends Base {
  constructor(data, systemTime, unionid) {
    super();

    this.defId = data.goodsDefId;
    this.modelId = data.goodsModelId;
    this.name = data.goodsName;
    this.pic = this.getOnePic(data.goodsPic);
    this.price = data.activityPrice;
    this.sourcePrice = data.goodsModelSourcePrice;
    this.unionid = unionid;
    this.discountedPrice = data.discountedPrice;
    this.isBargaining = data.isIn !== null;
    this.isPay = data.payOneYuanLast === 1;
    this.saledCount = data.saledCount;

    let discountedRate = data.disparity;
    this.discountedRate = parseFloat(discountedRate);

    this.maxRecord = 0;
    this.recordList = [];

    let startTime = moment(data.activityStartTime).valueOf();
    this.startTime = startTime;

    let endTime = moment(data.activityEndTime).valueOf();
    this.endTime = endTime;

    this.setType(systemTime);
  }

  setType(nowTime) {
    if (nowTime === undefined) {
      nowTime = moment();
    } else {
      nowTime = moment(nowTime)
    }

    let startTime = this.startTime;
    let endTime = this.endTime;
    let type;
    if (moment(nowTime).isBefore(startTime, 'second')) {
      type = 0;
    } else if (moment(nowTime).isAfter(endTime, 'second')) {
      type = 2;
    } else {
      type = 1;
    }
    this.type = type;
  }

  resetData(data) {
    let recordList = data.recordList;
    this.setRecordList(recordList);

    let goods = data.goods;
    if (goods === undefined) {
      return;
    }

    this.saledCount = goods.saledCount;
    this.price = goods.activityPrice;
    this.discountedPrice = goods.discountedPrice;
    let discountedRate = goods.disparity;
    this.discountedRate = parseFloat(discountedRate);
  }

  setRecordList(recordList) {
    if (recordList.length === 0) {
      return;
    }

    let records = [];
    let maxRecord = this.maxRecord;
    for (let i = 0; i < recordList.length; i++) {
      let record = recordList[i];
      let id = record.activityLogId;
      if (id <= maxRecord) {
        continue;
      }

      record = new BargainSituationRecord(record);
      records.push(record);
    }

    if (records.length > 0) {
      this.maxRecord = records[0].id;
      this.recordList.unshift(...records);
    }
  }

  getPayObject(){
    let postData = {
      goodsDefId: this.defId,
      goodsModelId: this.modelId,
      buyCount: 1,
      activityTypeId: 1
    };

    return postData;
  }
}
